(function () {
    app
        .controller('ratesCtrl', ['$rootScope', '$scope', 'RESTService', '$interval', '$timeout', '$state', function ($rootScope, $scope, RESTService, $interval, $timeout, $state) {
            $rootScope.selecInd = 1;
            $rootScope.showTabs = true;
            $scope.$on("$destroy", function () {
                $rootScope.showTabs = false;
                $interval.cancel(ratesInterval);
            });

            var loadData = function () {
                RESTService.getResponse('/rest/rate/getRates?').then(function (response) {
                    console.log(response);
                    $scope.rates = response.data;
                });
            };

            $timeout(function () {
                loadData();
            });

            var ratesInterval = $interval(function () {
                loadData();
            }, 30000);

            RESTService.getResponse('/rest/coupon/getAvailableCoupons?').then(function (res) {
                $scope.details = res.data;
                console.log($scope.details);
                $scope.redeemTitle = [];
                angular.forEach($scope.details, function (v) {
                    if (v.receivedMax > v.receivedCount) {
                        $scope.redeemTitle.push(v);
                    }
                });
            });

        }])

        .controller('analysisCtrl', ['$scope', 'RESTService', '$stateParams', '$interval', '$timeout', function ($scope, RESTService, $stateParams, $interval, $timeout) {
            console.log($stateParams.instrument);
            // 离开当前页面，销毁定时器
            $scope.$on('$destroy', function () {
                $interval.cancel(rateInterval);
            });
            var loadRateData = function () {
                RESTService.getResponse('/rest/rate/getRate?instrument=' + $stateParams.instrument).then(function (response) {
                    $scope.rate = response.data;
                });
            };

            $timeout(function () {
                loadRateData();
            });

            var rateInterval = $interval(function () {
                loadRateData();
            }, 30000);

            $scope.tabs = [
                {
                    key: 'M15',
                    title: '15分钟'
                },
                {
                    key: 'H1',
                    title: '1小时'
                },
                {
                    key: 'H4',
                    title: '4小时'
                },
                {
                    key: 'D',
                    title: '日'
                }
            ];

            $scope.getCandles = function (k) {
                RESTService.getResponse('/rest/candle/getCandle?instrument=' + $stateParams.instrument + '&granularity=' + k).then(function (res) {
                    console.log(res);
                    $scope.candle = res.data[0];
                });
            };
            RESTService.getResponse('/rest/candle/getCandle?instrument=' + $stateParams.instrument + '&granularity=D').then(function (res) {
                $scope.candle = res.data[0];
                console.log($scope.candle);

                RESTService.getResponse('/rest/candle/getCandles?instrument=' + $scope.candle.instrument
                    + '&granularity=D' + '&startTime=' + '&finishTime').then(function (response) {
                    console.log(response);
                    drawCandle(response.data);
                });
            });
            function drawCandle(myData) {
                // console.log(myData);
                // 基于准备好的dom，初始化echarts实例
                var myChart = echarts.init($('#main')[0]);

                function calculateMA(dayCount, data) {
                    var result = [];
                    for (var i = 0, len = data.length; i < len; i++) {
                        if (i < dayCount) {
                            result.push('-');
                            continue;
                        }
                        var sum = 0;
                        for (var j = 0; j < dayCount; j++) {
                            sum += data[i - j][1];
                        }
                        result.push(sum / dayCount);
                    }
                    return result;
                }


                // 时间
                var dates = myData.map(function (item) {
                    return item.updatedShow;
                });

                // 数据
                var data = myData.map(function (item) {
                    return [+item.open, +item.close, +item.low, +item.high, +item.changing + '%'];
                });

                // 标记
                var getMarkpoints = function (arr) {
                    // console.log(arr);
                    var markPoints = [];
                    for (var i = 0; i < arr.length; i++) {
                        if (arr[i].mark !== null) {
                            console.log(arr[i].mark);
                            markPoints.push({
                                name: arr[i].mark,
                                coord: [arr[i].updatedShow, arr[i].highask],
                                value: arr[i].mark,
                                itemStyle: {
                                    normal: {color: (arr[i].mark === 'B' ? 'green' : 'red')}
                                }
                            });
                        }
                    }
                    // console.log(markPoints);
                    return markPoints;
                };


                // 配置项
                var option = {
                    title: {
                        text: $scope.candle.instrument,
                        textStyle: {
                            color: '#fff',
                            fontSize: '10px'
                        }

                    },
                    backgroundColor: '#21202D',
                    legend: {
                        data: ['K线', 'MA3', 'MA5'],
                        inactiveColor: '#777',
                        textStyle: {
                            color: '#fff'
                        }
                    },
                    grid: {
                        left: '10%',
                        right: '10%',
                        bottom: '15%'
                    },
                    tooltip: {
                        trigger: 'axis',
                        transitionDuration: 0.4,
                        axisPointer: {
                            animation: true,
                            type: 'cross',
                            lineStyle: {
                                color: '#376df4',
                                width: 2,
                                opacity: 1
                            }
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLine: {lineStyle: {color: '#8392A5'}}
                    },
                    yAxis: {
                        scale: true,
                        axisLine: {lineStyle: {color: '#8392A5'}},
                        splitLine: {show: false}
                    },
                    dataZoom: [{
                        textStyle: {
                            color: '#8392A5'
                        },
                        handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                        handleSize: '80%',
                        dataBackground: {
                            areaStyle: {
                                color: '#8392A5'
                            },
                            lineStyle: {
                                opacity: 0.8,
                                color: '#8392A5'
                            }
                        },
                        handleStyle: {
                            color: '#fff',
                            shadowBlur: 3,
                            shadowColor: 'rgba(0, 0, 0, 0.6)',
                            shadowOffsetX: 2,
                            shadowOffsetY: 2
                        }
                    }, {
                        type: 'inside'
                    }],
                    animation: false,
                    series: [
                        {
                            type: 'candlestick',
                            name: 'K线',
                            data: data,
                            itemStyle: {
                                normal: {
                                    color: '#FD1050',
                                    color0: '#0CF49B',
                                    borderColor: '#FD1050',
                                    borderColor0: '#0CF49B'
                                }
                            },
                            markPoint: {
                                label: {
                                    normal: {
                                        formatter: function (param) {
                                            return param.value;
                                        }
                                    }
                                }
                                // data: getMarkpoints(myData)
                            },
                            markLine: {
                                symbol: ['none', 'none'],
                                precision: 5,
                                data: [
                                    // [
                                    //     {
                                    //         name: 'from lowest to highest',
                                    //         type: 'min',
                                    //         valueDim: 'lowest',
                                    //         symbol: 'circle',
                                    //         symbolSize: 10,
                                    //         label: {
                                    //             normal: {show: false},
                                    //             emphasis: {show: false}
                                    //         }
                                    //     },
                                    //     {
                                    //         type: 'max',
                                    //         valueDim: 'highest',
                                    //         symbol: 'circle',
                                    //         symbolSize: 10,
                                    //         label: {
                                    //             normal: {show: false},
                                    //             emphasis: {show: false}
                                    //         }
                                    //     }
                                    // ],
                                    // {
                                    //     name: 'stopLoss',
                                    //     yAxis: $scope.candle.stopLoss,
                                    //     itemStyle:{
                                    //         normal:{color:'red'}
                                    //     }
                                    // },
                                    // {
                                    //     name: 'takePerfit1,',
                                    //     yAxis: $scope.candle.takePerfit1,
                                    //     itemStyle:{
                                    //         normal:{color:'green'}
                                    //     }
                                    // },
                                    // {
                                    //     name: 'price',
                                    //     yAxis: $scope.candle.price,
                                    //     itemStyle:{
                                    //         normal:{color:'blue'}
                                    //     }
                                    // }
                                ]
                            }
                        },
                        {
                            name: 'MA3',
                            type: 'line',
                            data: calculateMA(3, data),
                            smooth: true,
                            showSymbol: false,
                            lineStyle: {
                                normal: {
                                    width: 1
                                }
                            },
                            tooltip: {
                                show: false
                            }
                        },
                        {
                            name: 'MA5',
                            type: 'line',
                            data: calculateMA(5, data),
                            smooth: true,
                            showSymbol: false,
                            lineStyle: {
                                normal: {
                                    width: 1
                                }
                            },
                            tooltip: {
                                show: false
                            }
                        }
                    ]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            }
        }])

        .controller('detailCtrl', ['$scope', '$stateParams', 'RESTService', function ($scope, $stateParams, RESTService) {
            $scope.instrument = $stateParams.instrument;
            RESTService.getResponse('/rest/instrument/getInstrumentDetail?instrument=' + $scope.instrument).then(function (response) {
                $scope.details = response;

                console.log(response.data[0]);
            })

        }])

        .controller('handleCtrl', ['$rootScope', '$scope', 'RESTService', function ($rootScope, $scope, RESTService) {
            RESTService.getResponse('/rest/instrument/getInstruments?').then(function (response) {
                // console.log(response);
                $scope.instruments = response.data;
            });

            $scope.followInstr = function (followname, ind) {
                console.log(followname);
                RESTService.getResponse('/rest/instrument/followInstrument?instrument=' + followname).then(function (response) {
                    $scope.instruments[ind].followed = true;
                })
            };

            $scope.cancelInstr = function (cancelname, ind) {
                console.log(cancelname);
                RESTService.getResponse('/rest/instrument/cancelInstrument?instrument=' + cancelname).then(function (response) {
                    $scope.instruments[ind].followed = false;
                })
            };
        }])
})();

